// kit-chart 根据输入生成图表
package main

import (
	_ "embed"
	"flag"
	"fmt"
	"os"
	"path"
	"strings"

	"gitee.com/xuender/kits/charts"
	"gitee.com/xuender/kits/cmd"
	"gitee.com/xuender/oils/logs"
	"github.com/golang/freetype/truetype"
	"github.com/wcharczuk/go-chart"
)

//go:embed HYQiHei-55S.ttf
var fontData []byte

// GetAssetFont 获取字体.
func GetAssetFont() *truetype.Font {
	font, err := truetype.Parse(fontData)
	if err != nil {
		panic(err)
	}

	return font
}

// nolint: gochecknoglobals
var (
	cliFile  string
	cliType  string
	cliName  string
	cliTitle string
	cliStyle string
)

func main() {
	// 扩展文件名
	ext := path.Ext(cliFile)
	// 未知扩展文件名按照类型设置
	if ext == "" {
		ext = cliType
		cliFile = cliFile + "." + cliType
	} else {
		ext = ext[1:]
	}

	simple := charts.NewSimple(cliTitle, GetAssetFont())

	for i := 0; i < flag.NArg(); i++ {
		simple.Add(flag.Arg(i))
	}

	file, _ := os.Create(cliFile)

	defer file.Close()
	// 创建图表
	var render charts.Render
	// 图表类型
	switch cliStyle {
	case "bar":
		render = simple.Bar()
	case "graph":
		render = simple.Graph()
	default:
		render = simple.Chart()
	}
	// SVG
	if strings.EqualFold(ext, "svg") {
		if err := render.Render(chart.SVG, file); err != nil {
			logs.Error(err)
		}

		return
	}
	// PNG
	if strings.EqualFold(ext, "png") {
		if err := render.Render(chart.PNG, file); err != nil {
			logs.Error(err)
		}

		return
	}
}

// nolint: gochecknoinits
func init() {
	flag.Usage = usage
	// 加载命令行
	flag.StringVar(&cliFile, "o", "chart", "Output chart file.")
	flag.StringVar(&cliName, "n", "", "Chart Name.")
	flag.StringVar(&cliType, "t", "svg", "File type[svg,png]")
	flag.StringVar(&cliTitle, "c", "", "Chart title.")
	flag.StringVar(&cliStyle, "s", "auto", "Chart Style [auto,bar,graph].")
	flag.Parse()
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "kit-chart [%s]\n\n", cmd.ModVersion)
	fmt.Fprintf(flag.CommandLine.Output(), "根据输出生成svg图表\n\n")
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(flag.CommandLine.Output(), "\n模块: %s\n提交: %s\n", cmd.ModPath, cmd.ModSum)
}
